<?php

namespace App\HttpController\Admin;

use Exception;
use EasySwoole\ORM\DbManager;

use App\Common\Tools;
use App\Model\User\User as UserModel;
use App\Common\Traits\Admin\ {
    Lists as AdminList,
    Info as AdminInfo,
    Create as AdminCreate,
};
use App\Validate\User as ValidateUser;
use App\Validate\Delete as ValidateDelete;

class User extends Base
{
    use AdminList;
    use AdminInfo;
    use AdminCreate;

    /**
     * @description: 模型
     * @var Model
     */
    public $model = UserModel::class;

    /**
     * @description: 主键
     * @var 
     */
    public $id = 'id';

     /**
     * @description: 删除
     * @param {*}
     * @return {*}
     */
    public function delete()
    {
        $result = DbManager::getInstance()->invoke(function ($client) {
            $param  = $this->request()->getRequestParam();
            $errMsg = (new ValidateDelete)->validate($param);
            if ($errMsg !== true) {
                throw new Exception($errMsg, 405);
            }
            $model = $this->model::invoke($client);
            $model->modifyData($param['id'], ['is_delete' => 1]);
            return true;
        });
        Tools::json($this->response(), 200, [], '数据删除完成');
    }

    /**
     * @description: 列表查询条件构建
     * @param array $param 前端参数
     * @return {*}
     */
    protected function indexWhere(array $param)
    {
        $where = [];
        Tools::conditionQuery($where, $param, 'username', 'username', 'like');
        return $where;
    }

    /**
     * @description: 列表查询条件默认字段
     * @param {*}
     * @return {*}
     */
    protected function indexDeafultParam()
    {
        return [
            'username' => '',
        ];
    }

    /**
     * @description: 验证创建参数
     * @param array $param 前端参数
     * @return {*}
     */
    protected function validateCreate(array $param)
    {
        $errMsg = (new ValidateUser)->validate($param);
        if ($errMsg !== true) {
            return $errMsg;
        }
        $result = DbManager::getInstance()->invoke(function ($client) use ($param) {
            $model = $this->model::invoke($client);
            $user  = $model->scopWhere()->where('username', $param['username'])->get();
            if ($user && $user['id'] != ($param['id'] ?? '')) {
                return '用户名重复';
            }
            return true;
        });
        return $result;
    }
}
